#include "CApp.h"
#include <iostream>
#include <fstream>
 
void CApp::OnLoop()
{
    // Clean out obsolete entities first
    for (std::list<CEntity*>::iterator it = CEntity::EntityList.begin(); it != CEntity::EntityList.end();)
    {
        if ((*it)->needsCleanup)
        {
            (*it)->OnCleanup();
            it = CEntity::EntityList.erase(it);
        }
        else
        {
            it++;
        }
    }

	// Call all of the OnLoops
    for (std::list<CEntity*>::iterator it = CEntity::EntityList.begin(); it != CEntity::EntityList.end(); it++)
    {
        (*it)->OnLoop();
    }

    // Next move everything and queue up collisions
    bool anyoneNeedsMove;
    do
    {
        anyoneNeedsMove = false;
        for (std::list<CEntity*>::iterator it = CEntity::EntityList.begin(); it != CEntity::EntityList.end(); it++)
        {
            if (((*it)->OnMove()))
            {
                anyoneNeedsMove = true;
            }
        }
        //checkForCollisions();
    } while (anyoneNeedsMove);


    // Handle Collision Events
    for(int i = 0;i < CEntityCol::EntityColList.size();i++)
    {
        CEntity* EntityA = CEntityCol::EntityColList[i].EntityA;
        CEntity* EntityB = CEntityCol::EntityColList[i].EntityB;
        if(EntityA == NULL || EntityB == NULL)
        {
            continue;
        }
        EntityA->OnCollision(EntityB);
        EntityB->OnCollision(EntityA);
    }
    CEntityCol::EntityColList.clear();
    
    CFPS::FPSControl.OnLoop();
}